import _ from 'lodash'
import {Message,Loading} from 'element-ui'
import axios from 'axios';
import fw from '../framework'
import config from '../../config/config'
let base = config.PARAM.API_BASE_URL;
let message = {
  success: function (msg) {
    Message.closeAll();
    Message({
      type: 'success',
      iconClass: 'none',
      customClass: 'lj-message-success',
      dangerouslyUseHTMLString: true,
      message: '<div class="lj-message-box"><span class="lj-message-icon"><i class="iconfont icon-chenggong"></i></span><span class="lj-message-text">' + msg + '</span></div>'
    })
  },
  error: function (msg) {
    Message.closeAll();
    Message({
      type: 'error',
      iconClass: 'none',
      customClass: 'lj-message-error',
      dangerouslyUseHTMLString: true,
      message: '<div class="lj-message-box"><span class="lj-message-icon"><i class="iconfont icon-shibai"></i></span><span class="lj-message-text">' + msg + '</span></div>'
    });
  }
};
let loading = function () {
  config.screen_page_loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
    fullscreen: true
  });
};
let closeLoading = function () {
  var $screen = document.querySelector('.is-fullscreen');
  if (config.screen_page_loading) {
    config.screen_page_loading.close();
  } else {
    if ($screen)
      $screen.remove();
  }
};
let user = {
  set(data){
    fw.utils.setCookie(config.cookieName.user, data, 7 * 24 * 60);
  },
  get(){
    return fw.utils.getCookie(config.cookieName.user) || {};
  },
  remove(){
    fw.utils.removeCookie(config.cookieName.user);
  },
  getToken(){
    return this.get().token;
  },
  getMobile(){
    return this.get().mobile;
  },
  getUserName(){
    return this.get().mobile;
  },
  getRole(){
    return this.get().role;
  }
};
function ajax() {
  let _api, params;
  if (arguments.length >= 2) {
    _api = arguments[0].indexOf('://') > -1 ? arguments[0] : (base + arguments[0]);
    params = arguments[1];

  } else {
    _api = base + arguments[0];
    params = {};
  }
  if (arguments.length == 3) {
    axios.defaults.headers['token'] = arguments[2];
  }
  //console.log(_api, params)
  console.log('', _api)
  return axios.post(_api, params).then((res) => {
    switch (res.data.code) {
      case 501:// 未登录
        goLogin();
        return {};
        break;
      case 513:
        message.error(res.data.msg || '程序异常，工程师正在修复……');
        return {};
      case 0:
        return res.data || {};
      default:
        var msg;
        if (config.ENV.toLowerCase() == 'prod') {
          msg = res.data.msg || '程序异常，工程师正在修复……';
        } else {
          msg = '接口：' + _api + ',异常信息：' + (res.data.msg || 'FE友情提示，未知错误');
        }
        message.error(msg);
        return res.data || {};
    }
  }).catch(ex => {
    try {
      message.error('网络异常，或者接口请求异常。接口：' + _api);
    } catch (e) {
      alert('网络异常，或者接口请求异常。接口：' + _api);
    }
  });
}
function goLogin() {
  window.location.href = '#/login';
}

function getQiniuToken(callbackFn, api) {
  let getToken = function () {
    ajax(api || config.apiName.uploadToken, {}).then((res)=> {
      if (res.data && res.data.uptoken) {
        config._qiniu_uptoken = {
          value: res.data.uptoken,
          time: new Date().getTime()
        };
        callbackFn(config._qiniu_uptoken.value);
      } else {
        fw.message.error('获取七牛上传的token失败')
      }
    });
  };
  if (!!config._qiniu_uptoken && config._qiniu_uptoken.value) {
    // 七牛的token时间超过半个小时，则重新请求
    if (new Date().getTime() - config._qiniu_uptoken.time > (30 * 60 * 1000)) {
      getToken();
    } else {
      callbackFn(config._qiniu_uptoken.value);
    }
  } else {
    getToken();
  }
}

function uploadQiniuByBase64(base64, callbackFn) {
  var pic = base64.indexOf('image/png;base64,') > -1 ? base64.substring(22) : base64;
  var url = "http://up.qiniu.com/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名
  var xhr = new XMLHttpRequest();
  getQiniuToken(function (token) {
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        callbackFn('http://s.swao.cn/'+JSON.parse(xhr.responseText).hash);
      }
    };
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    xhr.setRequestHeader("Authorization", "UpToken " + token);
    xhr.send(pic);
  });
}


let projectFramework = {
  message: message,
  ajax: ajax,
  user: user,
  loading: loading,
  closeLoading: closeLoading,
  config: config,
  getQiniuToken: getQiniuToken,
  uploadQiniuByBase64: uploadQiniuByBase64
};
projectFramework = _.defaultsDeep(projectFramework, fw);
export default projectFramework;
